import puppeteer from 'puppeteer-core';
import path from 'path';
import fs from 'fs';
import os from 'os'

const cwd = process.cwd()

const randomStr = (len = 8) => {
    return Math.random().toString(36).substring(2, 2 + len).toUpperCase()
}

function getDefaultPath() {
  const platform = os.platform()

  switch(platform) {
    case "win32": {
      return "C:/Program Files/Google/Chrome/Application/chrome.exe"
    }
    case "darwin": {
      return "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
    }
  }
  return ""
}

export async function captureScreenshot(config) {
  const browser = await puppeteer.launch({
    executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || getDefaultPath(),
    headless: true,
  });

  try {
    let filePath = path.join(cwd, 'dist', 'index.html');
    if (!fs.existsSync(filePath)) {
      filePath = path.join(cwd, 'index.html');
    }
    const htmlFile = filePath

    const page = await browser.newPage();
    await page.evaluateOnNewDocument((cfg) => {
      Object.assign(window, {
        _INJECT_CONFIG_: cfg,
      })
    }, config);
    
    await page.setJavaScriptEnabled(true);
    await page.setViewport({width: 600, height: 500, deviceScaleFactor: 3})
    await page.goto(htmlFile, { waitUntil: 'networkidle0' });

    // 截图并保存
    const outFilename = `PIC-${randomStr()}.jpg`
    const screenshotPath = path.join(cwd, 'images', outFilename);
    if (!fs.existsSync(path.dirname(screenshotPath))) {
      fs.mkdirSync(path.dirname(screenshotPath), { recursive: true });
    }

    await page.screenshot({
        type: 'jpeg',
        path: screenshotPath,
        fullPage: true,
        quality: 100,
        omitBackground: true,
    });
    
    return {
      filename: outFilename,
      screenshotPath
    };
  } finally {
    await browser.close();
  }
}